$(document).ready(function(){
	var imgX, imgY, imgW, imgH;
	var jcrop_api;
	
	$('#btCortarFoto').livequery('click',function(){
		$.post("pessoa/classes/cortarImagem.php",{
				fileName: $(this).prev().find('img').attr('src'),
				x: imgX,
				y: imgY,
				w: imgW,
				h: imgH
			},
			function(data){
				$('#txFoto').val(data);
				jcrop_api.setImage('pessoa/imagens/fotos/' + data);
			}
		);
		return false;
	});
	
	$('#btLimparFoto').livequery('click',function(){
		$('#txFoto').val('');
		$('#fotoFuncionario img').attr('src','');
		return false;
	});
	
	$.fn.createUploader = function(){
		var uploader = new qq.FileUploader({
			element: document.getElementById('txFotoField'),
	        action: 'pessoa/classes/gravarImagem.php',
	        //allowedExtensions: ['jpeg','jpg'],
	        //sizeLimit: 0, // bytes
	        //minSizeLimit: 0, // bytes
	        multiple: false,
	        onComplete: function(id, fileName, responseJSON){
	        	if($('ul.qq-upload-list li').length > 1) { $('ul.qq-upload-list li:eq(0)').remove(); }
	        	$('#txFoto').val(responseJSON.fileName);
	        	$('#fotoFuncionario').html('<img src="pessoa/imagens/fotos/' + responseJSON.fileName + '" /><button id="btCortarFoto">Cortar</button>');
	        	$('#fotoFuncionario img').Jcrop({onSelect: function(c){
	        		jcrop_api = this;
	        		imgX = c.x;
	        		imgY = c.y;
	        		imgW = c.w;
	        		imgH = c.h;
	        	}});
	        }
	    });
	}
	
	$().createUploader();
	// caso ja exista o registro (edição)
	if($('#txFoto').val())
	{
		$('#fotoFuncionario').append('<button id="btCortarFoto">Cortar</button><button id="btLimparFoto">Limpar</button>');
		$('#fotoFuncionario img').Jcrop({onSelect: function(c){
    		jcrop_api = this;
    		imgX = c.x;
    		imgY = c.y;
    		imgW = c.w;
    		imgH = c.h;
    	}});
	}
	
	$("#nmUsuario").autocomplete({
		source: '?c=CUsuario_buscarUsuarios&tipoResposta=json&ajax=true',
		dataType: 'json',
		select: function(event, ui) {
			$("#idUsuario").val(ui.item.value);
			$("#nmUsuario").val(ui.item.label);
			$("#nmUsuario").attr('disabled','disabled');
			$("#btLimparUsuario").css('display','inline-block');
			return false;
		}
	});
	$("#btLimparUsuario").click(function(){
		$("#nmUsuario").removeAttr('disabled');
		$("#nmUsuario").val('');
		$("#idUsuario").val('');
		$(this).css('display','none');
	});
	$("#dtNascimento").datepicker('option', 'changeMonth', true);
	$("#dtNascimento").datepicker('option', 'changeYear', true);
	$('#csPessoa').change(function(){
		local = $("#nrDocumento").parent();
		$('#nrDocumento').remove();
		$(local).append('<input title="CPF/CNPJ" class="numerico" size="27" value="" id="nrDocumento" name="nrDocumento" tabindex="1"/>');
		if($(this).val().charAt(0) == 'F') {
			$('#nrDocumento').mask("999.999.999-99",{completed:function(){}});
		}else{
			$('#nrDocumento').mask("99.999.999/9999-99",{completed:function(){}});
		}
	}).trigger('change');
});